/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Cpu;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Server;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.CpuCorePower;
import java.util.ArrayList;
import java.util.Collection;
import it.polimi.games.epkb.entityClasses.CpuCore;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class CpuJpaController implements Serializable {

    public CpuJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public CpuJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Cpu cpu) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (cpu.getCpuCorePowerCollection() == null) {
            cpu.setCpuCorePowerCollection(new ArrayList<CpuCorePower>());
        }
        if (cpu.getCpuCoreCollection() == null) {
            cpu.setCpuCoreCollection(new ArrayList<CpuCore>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = cpu.getComponent();
        if (componentOrphanCheck != null) {
            Cpu oldCpuOfComponent = componentOrphanCheck.getCpu();
            if (oldCpuOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type Cpu whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Server idServer = cpu.getIdServer();
            if (idServer != null) {
                idServer = em.getReference(idServer.getClass(), idServer.getId());
                cpu.setIdServer(idServer);
            }
            Component component = cpu.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                cpu.setComponent(component);
            }
            Collection<CpuCorePower> attachedCpuCorePowerCollection = new ArrayList<CpuCorePower>();
            for (CpuCorePower cpuCorePowerCollectionCpuCorePowerToAttach : cpu.getCpuCorePowerCollection()) {
                cpuCorePowerCollectionCpuCorePowerToAttach = em.getReference(cpuCorePowerCollectionCpuCorePowerToAttach.getClass(), cpuCorePowerCollectionCpuCorePowerToAttach.getId());
                attachedCpuCorePowerCollection.add(cpuCorePowerCollectionCpuCorePowerToAttach);
            }
            cpu.setCpuCorePowerCollection(attachedCpuCorePowerCollection);
            Collection<CpuCore> attachedCpuCoreCollection = new ArrayList<CpuCore>();
            for (CpuCore cpuCoreCollectionCpuCoreToAttach : cpu.getCpuCoreCollection()) {
                cpuCoreCollectionCpuCoreToAttach = em.getReference(cpuCoreCollectionCpuCoreToAttach.getClass(), cpuCoreCollectionCpuCoreToAttach.getId());
                attachedCpuCoreCollection.add(cpuCoreCollectionCpuCoreToAttach);
            }
            cpu.setCpuCoreCollection(attachedCpuCoreCollection);
            em.persist(cpu);
            if (idServer != null) {
                idServer.getCpuCollection().add(cpu);
                idServer = em.merge(idServer);
            }
            if (component != null) {
                component.setCpu(cpu);
                component = em.merge(component);
            }
            for (CpuCorePower cpuCorePowerCollectionCpuCorePower : cpu.getCpuCorePowerCollection()) {
                Cpu oldIdCPUOfCpuCorePowerCollectionCpuCorePower = cpuCorePowerCollectionCpuCorePower.getIdCPU();
                cpuCorePowerCollectionCpuCorePower.setIdCPU(cpu);
                cpuCorePowerCollectionCpuCorePower = em.merge(cpuCorePowerCollectionCpuCorePower);
                if (oldIdCPUOfCpuCorePowerCollectionCpuCorePower != null) {
                    oldIdCPUOfCpuCorePowerCollectionCpuCorePower.getCpuCorePowerCollection().remove(cpuCorePowerCollectionCpuCorePower);
                    oldIdCPUOfCpuCorePowerCollectionCpuCorePower = em.merge(oldIdCPUOfCpuCorePowerCollectionCpuCorePower);
                }
            }
            for (CpuCore cpuCoreCollectionCpuCore : cpu.getCpuCoreCollection()) {
                Cpu oldIdCPUOfCpuCoreCollectionCpuCore = cpuCoreCollectionCpuCore.getIdCPU();
                cpuCoreCollectionCpuCore.setIdCPU(cpu);
                cpuCoreCollectionCpuCore = em.merge(cpuCoreCollectionCpuCore);
                if (oldIdCPUOfCpuCoreCollectionCpuCore != null) {
                    oldIdCPUOfCpuCoreCollectionCpuCore.getCpuCoreCollection().remove(cpuCoreCollectionCpuCore);
                    oldIdCPUOfCpuCoreCollectionCpuCore = em.merge(oldIdCPUOfCpuCoreCollectionCpuCore);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCpu(cpu.getId()) != null) {
                throw new PreexistingEntityException("Cpu " + cpu + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Cpu cpu) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cpu persistentCpu = em.find(Cpu.class, cpu.getId());
            Server idServerOld = persistentCpu.getIdServer();
            Server idServerNew = cpu.getIdServer();
            Component componentOld = persistentCpu.getComponent();
            Component componentNew = cpu.getComponent();
            Collection<CpuCorePower> cpuCorePowerCollectionOld = persistentCpu.getCpuCorePowerCollection();
            Collection<CpuCorePower> cpuCorePowerCollectionNew = cpu.getCpuCorePowerCollection();
            Collection<CpuCore> cpuCoreCollectionOld = persistentCpu.getCpuCoreCollection();
            Collection<CpuCore> cpuCoreCollectionNew = cpu.getCpuCoreCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                Cpu oldCpuOfComponent = componentNew.getCpu();
                if (oldCpuOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type Cpu whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idServerNew != null) {
                idServerNew = em.getReference(idServerNew.getClass(), idServerNew.getId());
                cpu.setIdServer(idServerNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                cpu.setComponent(componentNew);
            }
            Collection<CpuCorePower> attachedCpuCorePowerCollectionNew = new ArrayList<CpuCorePower>();
            for (CpuCorePower cpuCorePowerCollectionNewCpuCorePowerToAttach : cpuCorePowerCollectionNew) {
                cpuCorePowerCollectionNewCpuCorePowerToAttach = em.getReference(cpuCorePowerCollectionNewCpuCorePowerToAttach.getClass(), cpuCorePowerCollectionNewCpuCorePowerToAttach.getId());
                attachedCpuCorePowerCollectionNew.add(cpuCorePowerCollectionNewCpuCorePowerToAttach);
            }
            cpuCorePowerCollectionNew = attachedCpuCorePowerCollectionNew;
            cpu.setCpuCorePowerCollection(cpuCorePowerCollectionNew);
            Collection<CpuCore> attachedCpuCoreCollectionNew = new ArrayList<CpuCore>();
            for (CpuCore cpuCoreCollectionNewCpuCoreToAttach : cpuCoreCollectionNew) {
                cpuCoreCollectionNewCpuCoreToAttach = em.getReference(cpuCoreCollectionNewCpuCoreToAttach.getClass(), cpuCoreCollectionNewCpuCoreToAttach.getId());
                attachedCpuCoreCollectionNew.add(cpuCoreCollectionNewCpuCoreToAttach);
            }
            cpuCoreCollectionNew = attachedCpuCoreCollectionNew;
            cpu.setCpuCoreCollection(cpuCoreCollectionNew);
            cpu = em.merge(cpu);
            if (idServerOld != null && !idServerOld.equals(idServerNew)) {
                idServerOld.getCpuCollection().remove(cpu);
                idServerOld = em.merge(idServerOld);
            }
            if (idServerNew != null && !idServerNew.equals(idServerOld)) {
                idServerNew.getCpuCollection().add(cpu);
                idServerNew = em.merge(idServerNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setCpu(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setCpu(cpu);
                componentNew = em.merge(componentNew);
            }
            for (CpuCorePower cpuCorePowerCollectionOldCpuCorePower : cpuCorePowerCollectionOld) {
                if (!cpuCorePowerCollectionNew.contains(cpuCorePowerCollectionOldCpuCorePower)) {
                    cpuCorePowerCollectionOldCpuCorePower.setIdCPU(null);
                    cpuCorePowerCollectionOldCpuCorePower = em.merge(cpuCorePowerCollectionOldCpuCorePower);
                }
            }
            for (CpuCorePower cpuCorePowerCollectionNewCpuCorePower : cpuCorePowerCollectionNew) {
                if (!cpuCorePowerCollectionOld.contains(cpuCorePowerCollectionNewCpuCorePower)) {
                    Cpu oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower = cpuCorePowerCollectionNewCpuCorePower.getIdCPU();
                    cpuCorePowerCollectionNewCpuCorePower.setIdCPU(cpu);
                    cpuCorePowerCollectionNewCpuCorePower = em.merge(cpuCorePowerCollectionNewCpuCorePower);
                    if (oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower != null && !oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower.equals(cpu)) {
                        oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower.getCpuCorePowerCollection().remove(cpuCorePowerCollectionNewCpuCorePower);
                        oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower = em.merge(oldIdCPUOfCpuCorePowerCollectionNewCpuCorePower);
                    }
                }
            }
            for (CpuCore cpuCoreCollectionOldCpuCore : cpuCoreCollectionOld) {
                if (!cpuCoreCollectionNew.contains(cpuCoreCollectionOldCpuCore)) {
                    cpuCoreCollectionOldCpuCore.setIdCPU(null);
                    cpuCoreCollectionOldCpuCore = em.merge(cpuCoreCollectionOldCpuCore);
                }
            }
            for (CpuCore cpuCoreCollectionNewCpuCore : cpuCoreCollectionNew) {
                if (!cpuCoreCollectionOld.contains(cpuCoreCollectionNewCpuCore)) {
                    Cpu oldIdCPUOfCpuCoreCollectionNewCpuCore = cpuCoreCollectionNewCpuCore.getIdCPU();
                    cpuCoreCollectionNewCpuCore.setIdCPU(cpu);
                    cpuCoreCollectionNewCpuCore = em.merge(cpuCoreCollectionNewCpuCore);
                    if (oldIdCPUOfCpuCoreCollectionNewCpuCore != null && !oldIdCPUOfCpuCoreCollectionNewCpuCore.equals(cpu)) {
                        oldIdCPUOfCpuCoreCollectionNewCpuCore.getCpuCoreCollection().remove(cpuCoreCollectionNewCpuCore);
                        oldIdCPUOfCpuCoreCollectionNewCpuCore = em.merge(oldIdCPUOfCpuCoreCollectionNewCpuCore);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = cpu.getId();
                if (findCpu(id) == null) {
                    throw new NonexistentEntityException("The cpu with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cpu cpu;
            try {
                cpu = em.getReference(Cpu.class, id);
                cpu.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cpu with id " + id + " no longer exists.", enfe);
            }
            Server idServer = cpu.getIdServer();
            if (idServer != null) {
                idServer.getCpuCollection().remove(cpu);
                idServer = em.merge(idServer);
            }
            Component component = cpu.getComponent();
            if (component != null) {
                component.setCpu(null);
                component = em.merge(component);
            }
            Collection<CpuCorePower> cpuCorePowerCollection = cpu.getCpuCorePowerCollection();
            for (CpuCorePower cpuCorePowerCollectionCpuCorePower : cpuCorePowerCollection) {
                cpuCorePowerCollectionCpuCorePower.setIdCPU(null);
                cpuCorePowerCollectionCpuCorePower = em.merge(cpuCorePowerCollectionCpuCorePower);
            }
            Collection<CpuCore> cpuCoreCollection = cpu.getCpuCoreCollection();
            for (CpuCore cpuCoreCollectionCpuCore : cpuCoreCollection) {
                cpuCoreCollectionCpuCore.setIdCPU(null);
                cpuCoreCollectionCpuCore = em.merge(cpuCoreCollectionCpuCore);
            }
            em.remove(cpu);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Cpu> findCpuEntities() {
        return findCpuEntities(true, -1, -1);
    }

    public List<Cpu> findCpuEntities(int maxResults, int firstResult) {
        return findCpuEntities(false, maxResults, firstResult);
    }

    private List<Cpu> findCpuEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Cpu.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Cpu findCpu(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cpu.class, id);
        } finally {
            em.close();
        }
    }

    public int getCpuCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Cpu> rt = cq.from(Cpu.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
